/**
 * @file     removeDuplicates.js
 * @brief    [26. 删除有序数组中的重复项](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/)
 * @brief    [80. 删除有序数组中的重复项 II](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/)
 * @author   Zhu
 * @date     2022-03-14 17:19
 */

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
    if (nums.length === 0) return 0;
    let i = 0;
    for (const num of nums) {
        if (nums[i] !== num) {
            nums[++i] = num;
        }
    }
    return i + 1;
};

/**
 * 最多出现k次
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var removeDuplicates = function (nums, k) {
    let i = 0;
    for (const num of nums) {
        if (i < k || nums[i - k] !== num) {
            nums[i++] = num;
        }
    }
    return i;
};

/**
 * 最多出现K次的通用解法
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function (nums) {
    var removeMoreThan = function (nums, k) {
        if (nums.length <= k) return nums.length;
        let i = k; // waiting 位置
        for (let j = k; j < nums.length; j++) {
            const noMore = nums[i - k]; // [noMore, ..., waiting) 之间不能再有noMore
            const waiting = nums[j];
            if (waiting !== noMore) {
                nums[i++] = waiting;
            }
        }
        return i;
    };

    return removeMoreThan(nums, 2);
};
